package com.shi.vueblog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public class FileUploadUtils {

    public static File upload(MultipartFile multipartFile,String basePath){
        // 文件存储位置，文件的目录要存在才行，可以先创建文件目录，然后进行存储
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String now=df.format(LocalDateTime.now());
        String fileName= now+"_"+multipartFile.getOriginalFilename();
        File file=new File(basePath,fileName);
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
// 文件存储
            try {
                multipartFile.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }
}
